#include <string>
#include <vector>
#include <map>
#include "DFA.h"
#include <iostream>
#include "ebnf2bnf.h"
void test_dfa() {
    // 定义文法
    /*std::map<std::string, std::vector<std::string>> grammar = {
        {"S'", {"S"}},
        {"S", {"A"}},
        {"A", {"aA", "b"}}
    };
    std::map<std::pair<int, char>, int> transitionTable;
    constructDFA(grammar, transitionTable);*/
    std::map<int, std::vector<std::vector<int>>> grammar = {
        {2,    {{3,    1000, 1002, -5,   1004}}},
        {4,    {{1006}}},
        {1000, {{5,    3,    1000}, {0}}},
        {1002, {{4,    1002}, {4}}},
        {1004, {{7},          {0}}},
        {1006, {{5,    1006}, {5}}}
    };

    std::vector<std::set<Item>> states;
    std::map<std::pair<int, int>, int> transitionTable;

    // 构造并打印 DFA
    constructDFA(grammar, states, transitionTable);

    for (size_t i = 0; i < states.size(); ++i) {
        printState(i, states[i]);
    }
    printDFA(transitionTable);


}

void test_ebnf2bnf() {
    Ebnf2BnfConverter converter;
    Ebnf2BnfConverter::GrammarEBNF ebnf;
    // 示例：2 -> 3 (5 3)* 4+ | 7?  
    // 用负数标记：3,-1,5,-2,-3,4,-4,-5,7,-6
    ebnf[2] = { 3, -1, 5, 3, -2, -3, 4, -4, -5, 7, -6 };
    // 示例：4 -> 5+
    ebnf[4] = { 5, -4 };

    converter.setGrammar(ebnf);
    converter.convert();

    auto bnf = converter.getBnfGrammar(); // return GrammarBNF  std::map<int, std::vector<std::vector<int>>>;
    for (auto& pr : bnf) {
        int lhs = pr.first;
        for (auto& rhs : pr.second) {
            std::cout << lhs << " -> ";
            if (rhs.empty()) std::cout << "ε";
            else for (int tok : rhs) std::cout << tok << ' ';
            std::cout << std::endl;
        }
    }

}

void from_ebnf2dfa() {
    Ebnf2BnfConverter converter;
    Ebnf2BnfConverter::GrammarEBNF ebnf;
    // 示例：2 -> 3 (5 3)* 4+ | 7?  
    // 用负数标记：3,-1,5,-2,-3,4,-4,-5,7,-6
    ebnf[2] = { 3, -1, 5, 3, -2, -3, 4, -4, -5, 7, -6 };
    // 示例：4 -> 5+
    ebnf[4] = { 5, -4 };

    converter.setGrammar(ebnf);
    converter.convert();
    auto bnf = converter.getBnfGrammar(); // return GrammarBNF  std::map<int, std::vector<std::vector<int>>>;
    std::vector<std::set<Item>> states;
    std::map<std::pair<int, int>, int> transitionTable;

    // 构造并打印 DFA
    constructDFA(bnf, states, transitionTable);
    for (size_t i = 0; i < states.size(); ++i) {
        printState(i, states[i]);
    }
    printDFA(transitionTable);
}

int main() {
    //test_dfa();
    from_ebnf2dfa();
    return 0;
}
